<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="/data/resource/js/jquery.js"></script>
    <script>
        function addCookie(e, t, a) {
            var n = e + "=" + escape(t) + "; path=/";
            if (a > 0) {
                var r = new Date;
                r.setTime(r.getTime() + a * 3600 * 1e3);
                n = n + ";expires=" + r.toGMTString()
            }
            document.cookie = n
        }
        function getcookie(name) {
            var strcookie = document.cookie;
            var arrcookie = strcookie.split("; ");
            for (var i = 0; i < arrcookie.length; i++) {
                var arr = arrcookie[i].split("=");
                if (arr[0] == name)return arr[1];
            }
            return "";
        }

        function delCookie(name) {//删除cookie
            var exp = new Date();
            exp.setTime(exp.getTime() - 1);
            var cval = getcookie(name);
            if (cval != null) document.cookie = name + "=" + cval + "; path=/;expires=" + exp.toGMTString();
        }
    </script>
</head>
<body>
</body>
</html>
<?php

    require_once dirname(__DIR__) . '/core.php';
    require_once dirname(__DIR__) . '/jssdk/jssdk.php';

    require_wechat();

    require_once $_SERVER['DOCUMENT_ROOT'] . '/wxpay/lib/WxPay.JsApiPay.php';

    $js = new JsApiPay();
    $open_id = $js->GetOpenid();
    if (empty($open_id)) {
        header("location:/wap/tmpl/member/login.php?ref=" . $_GET['ref']);
        exit;
    }

    $wechat = new WeChat(-1);
    $appid = $wechat->config['appid'];
    $config = $wechat->config;
    $jssdk = new JSSDK($appid, $config['appsecret']);
    $access_token = $jssdk->getAccessToken();

    do {
        if ($user_info['errcode'] == 40001) {
            $access_token = $jssdk->getAccessToken(true);
        }
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$open_id&lang=zh_CN";
        $result = $jssdk->httpGet($url);
        $user_info = json_decode($result, true);

    } while ($user_info['errcode'] == 40001);


    if (empty($user_info['nickname'])) {
        header("location:/wap/tmpl/member/login.php?ref=" . $_GET['ref']);
        exit;
    }

    $_SESSION['wechat_user_info'] = $user_info;

    //looking for if this user has a account from out website
    $member = Model()->table('member')->where(array('wechat_openid' => $user_info['openid']))->find();

    $member_name = "wechat_" . $user_info['nickname'] . rand(100000, 999900);

    $um = Model('member');

    //如果不存在这个账户
    if (!$member) {
        //create a account
        $insert_array = array();
        $insert_array['member_name'] = trim($member_name);
        $insert_array['member_passwd'] = trim(1234567);
        $insert_array['member_email'] = trim('');
        $insert_array['member_truename'] = trim($user_info['nickname']);
        $insert_array['member_sex'] = trim('');
        $insert_array['member_qq'] = trim('');
        $insert_array['member_ww'] = trim('');
        $insert_array['nickname'] = trim($user_info['nickname']);
        $insert_array['wechat_openid'] = $open_id;
        $result = $um->addMember($insert_array);
        Model("points")->savePointsLog('regist',array('pl_memberid'=>$result,'pl_membername'=>$member_name),true);
        $headimgurl = $user_info['headimgurl'];//用户头像，最后一个数值代表正方形头像大小（有0、46、64、96、132数值可选，0代表640*640正方形头像）
//        $headimgurl = substr($headimgurl, 0, -1).'132';
//        $avatar = @copy($headimgurl,BASE_UPLOAD_PATH.'/'.ATTACH_AVATAR."/avatar_$result.jpg");
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $headimgurl);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
        $img = curl_exec($ch);
        for($i=0;$i<3;$i++){
            if($img!=''){
                break;
            }else{
                $img = curl_exec($ch);
            }
        }
        curl_close($ch);
        if($img != ''){
            $filename = $_SERVER['DOCUMENT_ROOT'].'/data/upload/shop/avatar/avatar_'.$result.'.jpg';
            $fp = fopen("$filename", "w+"); //打开文件指针，创建文件
            fwrite($fp,$img);
            fclose($fp); //关闭指针
        }
        if(filesize($filename)>0) {
            Model('member')->editMember(array('member_id'=> $result),array('member_avatar'=> "avatar_$result.jpg"));
        }
    } else {
        $result = $member['member_id'];
    }
    Model("points")->savePointsLog('login',array('pl_memberid'=>$result,'pl_membername'=>$member_name),true);

    if ($result) {
        $member_info = ml('member')->find($result);
        $token = _get_token($result, $member_name, 'wap');
        dis_log("假如分销插件未开启，那么不会出现以下的信息<br>") ;
        if (dis_open()) {
            dis_log( "分销插件已开启<br>");
            $dis = Distribute::getPreParent($result);
            if ($dis) {
                dis_log( "上级会员的实例是：<br>");
                dis_log( "上级会员的ID是：" . $dis->getMemberId() . "<br>");
                dis_log( "上级会员的层级是:" . $dis->getLevel() . "<br>");
                dis_log( "进入添加买家方法<br>");
                $dis->addBuyer($result);
            }
        }

        ?>
        <script>
            delCookie('key');
            delCookie('member_id');
            addCookie("key", '<?php echo $token;?>');
            addCookie("member_id", '<?php echo $member_info['member_id']?>');
            sessionStorage.is_login = 1;
            location.href = '<?php echo urldecode($_GET['ref'])?>';
        </script>
        <?php
        exit;
    }

?>

